package com.example.easyexcel.excelNew.service;

import com.alibaba.excel.annotation.ExcelProperty;
import com.example.easyexcel.excelNew.ExcelCheckResult;
import com.example.easyexcel.excelNew.ExcelImportErrDto;
import com.example.easyexcel.excelNew.UserImportVo;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserSerVice {
    public static final String ERR_NAME = "sb";
    @Override
    public ExcelCheckResult checkImportExcel(List<UserImportVo> userList) {
        //成功结果集
        List<UserImportVo> successList = new ArrayList<>();
        //错误数组
        List<ExcelImportErrDto> errList = new ArrayList<>();
        Map<Integer,String> cellErrColMap= new HashMap<>();
        for (int i = 0;i<userList.size() ;i++) {
            UserImportVo user = userList.get(i);
            //错误信息
            //根据自己的业务去做判断
            if (ERR_NAME.equals(user.getName())){
                try {
                    //获取当前字段对应的索引
                    int index = UserImportVo.class.getDeclaredField("name").getAnnotation(ExcelProperty.class).index();
                    cellErrColMap.put(index,"请输入正确的名字");
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
            if (cellErrColMap.size()==0){
                //没有错误信息 保存到成功列表
                successList.add(user);
            }else{
                //保存到错误列表
                errList.add(new ExcelImportErrDto(user,cellErrColMap));
            }
        }
        //在这里将校验成功的数据批量写入数据库
        System.out.println(successList.toString());
        return new ExcelCheckResult(errList);
    }
}
